import { useCallback } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import type { RootState, AppDispatch } from '../store';
import {
  fetchBorrows,
  createBorrow,
  updateBorrow,
  deleteBorrow,
  clearError
} from '../store/slices/borrowSlice';
import type {
  CreateBorrowRequest as SliceCreateBorrowRequest,
  UpdateBorrowRequest as SliceUpdateBorrowRequest
} from '../store/slices/borrowSlice';

export const useBorrow = () => {
  const dispatch = useDispatch<AppDispatch>();

  // 从 Redux store 中获取状态，useBorrow 不存储数据
  const { borrows, loading, error } = useSelector((state: RootState) => state.borrow);

  const initBorrows = useCallback(() => {
    dispatch(fetchBorrows());
  }, [dispatch]);

  const refreshBorrows = useCallback(() => {
    dispatch(fetchBorrows());
  }, [dispatch]);

  const addBorrow = useCallback(async (borrowData: SliceCreateBorrowRequest) => {
    try {
      const result = await dispatch(createBorrow(borrowData)).unwrap();
      return result;
    } catch (error) {
      console.error('添加借用记录失败:', error);
      throw error;
    }
  }, [dispatch]);

  const modifyBorrow = useCallback(async (borrowData: SliceUpdateBorrowRequest) => {
    try {
      const result = await dispatch(updateBorrow(borrowData)).unwrap();
      return result;
    } catch (error) {
      console.error('更新借用记录失败:', error);
      throw error;
    }
  }, [dispatch]);

  const removeBorrow = useCallback(async (borrowId: number) => {
    try {
      await dispatch(deleteBorrow(borrowId)).unwrap();
      return true;
    } catch (error) {
      console.error('删除借用记录失败:', error);
      throw error;
    }
  }, [dispatch]);

  const returnBorrow = useCallback(async (borrowId: number) => {
    try {
      // 使用 modifyBorrow 来更新记录状态为 'returned'
      const result = await dispatch(updateBorrow({
        id: borrowId,
        status: 'returned',
        actualReturn: new Date().toISOString().split('T')[0] // 设置实际归还日期为今天
      })).unwrap();
      return result;
    } catch (error) {
      console.error('归还物资失败:', error);
      throw error;
    }
  }, [dispatch]);

  const clearBorrowError = useCallback(() => {
    dispatch(clearError());
  }, [dispatch]);

  return {
    borrows,
    loading,
    error,
    initBorrows,
    refreshBorrows,
    createBorrow: addBorrow,
    modifyBorrow,
    removeBorrow,
    returnBorrow,
    clearError: clearBorrowError,
  };
};